<?php

namespace App\Repository\Lib;


use App\Repository\Common\ConstTable;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;



class Weixin
{

    //获取吊起微信支付参数
    static public function getWxPayConfig($order_type, $money, $order_id, $openid)
    {

        $app = new Application(config('app.weixin_options'));
        $payment = $app->payment;

        //创建订单
        $attributes = [
            'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
            'body' => '用户' . ConstTable::ORDER_TYPE[$order_type],
            'detail' => '用户' . ConstTable::ORDER_TYPE[$order_type],
            'out_trade_no' => 'ORDER_'.$order_id,
            'total_fee' => bcmul($money, 100, 0),
            'openid' => $openid
        ];
        Log::info("请求生成订单:".json_encode($attributes));
       
        $order = new Order($attributes);
        //统一下单
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
            $config['timestamp'] = (int)$config['timestamp'];
            return $config;
        } else {
//            var_dump($result);
            Log::error("微信支付错误: {$result->return_code}  ------ {$result->return_msg}" );
            return false;
        }
    }



    //微信支付成功通知模板
    static public function weixinNotice($openid, $templateId, $order_id)
    {

        /*
         * 模板
您好，您已消费成功。

消费金额：{{pay.DATA}}
消费地址：{{address.DATA}}
消费时间：{{time.DATA}}
{{remark.DATA}}
        */
        $order_info = Pay::OrderInfo($order_id);
        $app = new Application(Common::getWeixinOptions());
        $notice = $app->notice;
        $userId = $openid;
        $url = ServiceManager::getConfig('url') . '/web/user/consumptiondetailed?order_id=' . $order_id;
        $data = array(
            "pay" => "{$order_info['money']}元",
            "address" => "异吧",
            "time" => date('Y年m月d日 H:i'),
            "remark" => "欢迎下次光临！",
        );


        try {
            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
        } catch (\Exception $e) {
            Logger::writeLog("微信支付推送消息失败,openid: {$openid},错误消息" . $e->getMessage());
            return false;
        }
        Logger::writeLog("微信支付成功推送消息" . $result);
        return true;
        // var_dump($result);
// {
//      "errcode":0,
//      "errmsg":"ok",
//      "msgid":200228332
//  }


    }

}